using System;
using System.Collections;
using System.Collections.Generic;
using JufGame.AI;
using TMPro;
using UnityEngine;

namespace JufGame
{
	public class TestItem : MonoBehaviour
	{
		public OctreeBuilder octree;
		private AStar_Searcher<MyGraph<OctreeNode, int>, OctreeNode> astar;
		private Stack<OctreeNode> path;
		[SerializeField] private Transform start;
		[SerializeField] private Transform trackPoint;
		[SerializeField] private Transform end;
		private Vector3 nextPos;
		[SerializeField] private bool isOneTime;
		[SerializeField] private bool isShowPath;
		private bool isTrack;
		public void ButtonTest()
		{
			isOneTime = false;
		}

		public void TrackPath()
		{
			if(path.Count > 0 && !isTrack)
			{
				isTrack = true;
				nextPos = path.Pop().NodeBounds.center;
			}
		}

		private void Start()
		{
			astar = new AStar_Searcher<MyGraph<OctreeNode, int>, OctreeNode>(octree.NavGraph);
			path = new Stack<OctreeNode>();
		}
		private void Update()
		{
			if(!isOneTime)
			{
				var s = octree.Octree.GetNodeByPos(octree.Octree.RootNode, start.position);
				var e = octree.Octree.GetNodeByPos(octree.Octree.RootNode, end.position);
				astar.FindPath(s, e, path);
				trackPoint.position = start.position;
				isOneTime = true;
				isTrack = false;
			}
			if(isTrack)
			{
				trackPoint.position = Vector3.MoveTowards(trackPoint.position, nextPos, 0.001f);
				if(Vector3.SqrMagnitude(trackPoint.position - nextPos) < 0.01)
				{
					isTrack = false;
				}
			}
		}
		private void OnDrawGizmos()
		{
			if(Application.isPlaying && isShowPath)
			{
				var prevPos = start.position;
				foreach(var n in path)
				{
					Gizmos.color = Color.red;
					Gizmos.DrawLine(prevPos, n.NodeBounds.center);
					prevPos = n.NodeBounds.center;
				}
				Gizmos.DrawLine(prevPos, end.position);
			}
		}
	}
}
